package com.cmy.core.processor;

import com.cmy.core.pipeline.IqiyiLivePipeline;
import org.apache.commons.collections.map.HashedMap;
import org.junit.Test;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.model.HttpRequestBody;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.JsonPathSelector;
import us.codecraft.webmagic.utils.HttpConstant;

import java.util.List;
import java.util.Map;

public class IqiyiLiveProcessor implements PageProcessor {


    // 部分一：抓取网站的相关配置，包括编码、抓取间隔、重试次数等
    private Site site = Site.me()
            .setRetryTimes(3)
            .setSleepTime(500)
//            .addHeader("referer", "https://m-live.iqiyi.com/")
//            .addHeader("content-type","application/x-www-form-urlencoded; charset=UTF-8")
//            .addHeader("cache-control", "no-cache")
            .setUserAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36");

    @Override
    public void process(Page page) {
        /*Json json = page.getJson();
        Map resultMap = json.toObject(Map.class);
        Map dataMap = (Map) resultMap.get("data");
        List<Map> dataMapList = (List<Map>) dataMap.get("list");
        for (int i = 0; i < dataMapList.size(); i++) {
            System.out.println("\t" + dataMapList.get(i));
        }*/
        List<String> dataList = new JsonPathSelector("$.data.list[*].showRoomId").selectList(page.getRawText());
        while (dataList.size() > 0) {
            page.putField("dataList", dataList);
//            init(, 10);
        }

    }

    @Override
    public Site getSite() {
        return site;
    }

    @Test
    public void main() {
        init(1, 10);
    }

    public void init(Integer pageNum, Integer rows) {
        Request request = new Request();
        request.setUrl("https://gamelive.iqiyi.com/api/v1/liveList/list");
        request.setMethod(HttpConstant.Method.POST);
        Map<String, Object> params = new HashedMap();
        params.put("page", pageNum);
        params.put("rows", rows == null ? 20 : rows);
        params.put("liveTypeId", 4);
        request.addHeader("content-type", "application/x-www-form-urlencoded; charset=UTF-8");
        request.setRequestBody(HttpRequestBody.form(params, "utf-8"));

        Spider.create(new IqiyiLiveProcessor())
                //从"https://github.com/code4craft"开始抓
//                .addUrl("https://gamelive.iqiyi.com/api/v1/liveList/list")
                .addRequest(request)
//                .addPipeline(new ConsolePipeline())
                .addPipeline(new IqiyiLivePipeline())
                //开启5个线程抓取
                .thread(3)
                //启动爬虫
                .run();
    }
}
